package com.qingxin.wuye.repertory.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import com.qingxin.sys.dao.Querier;
import com.qingxin.sys.dao.Updater;
import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.mvc.PageParam;
import com.qingxin.sys.mvc.Pager;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.service.BaseService;
import com.qingxin.sys.support.JsTreeNode;
import com.qingxin.sys.support.SystemCfg;
import com.qingxin.sys.utils.BeanUtil;
import com.qingxin.sys.utils.StringUtils;
import com.qingxin.wuye.repertory.entity.Repertory;

@Service
public class RepertoryService extends BaseService<Repertory, String>{

	

	
	@SuppressWarnings("unchecked")
	public List<JsTreeNode> getUITreeData(LoginUser loginUser, boolean isParent){
		List<JsTreeNode> list = new ArrayList<>();
		if(loginUser == null){
			return list;
		}
		StringBuilder hql = new StringBuilder();
		hql.append("from Repertory where 1=1 ");
		hql.append(" order by name asc");
		List<Repertory> repertories = listByHql(hql.toString());
		if(repertories != null){
			for(Repertory repertory : repertories){
				list.add(new JsTreeNode(repertory.getRepertoryid(),repertory.getName(), SystemCfg.UI_DATATYPE_REPERTORY, "repertoryid", isParent));
			}
		}
		return list;
	}
	
	
	
	
	public Pager list(String searchname, PageParam pageParam, LoginUser loginUser){
		Querier querier = Querier.create("from Repertory");
		if(StringUtils.isNotEmpty(searchname)){
			searchname = searchname.replace("'", "");
			querier.append(" and name like :name ");
			querier.setParam("name", "%"+searchname+"%");
		}
		querier.append(pageParam.getOrderby(" order by createTime desc"));
		Pager pager = pageByQuerier(querier, pageParam);
		return pager;
		
	}
	
	
	public SysError add(Repertory repertory, LoginUser loginUser, HttpServletRequest request){
		repertory.setCreateTime(new Date());
		repertory.setCreateBy(loginUser.getLogin_name());
		this.save(repertory);
		return null;
	}
	
	public SysError update(Repertory repertory, LoginUser loginUser, HttpServletRequest request){
		Repertory old = getSafeEntity(repertory.getRepertoryid());
		String fields = "code,name,address,person,phone,remark";
		BeanUtil.setTargetFields(old, repertory, fields, true);
		Updater<Repertory> updater = new Updater<>(old, fields);
		this.update(updater);
		return null;
	}
	
	
	public Object delete(String[] repertoryid, LoginUser loginUser, HttpServletRequest request){
		for(String id : repertoryid){
			Repertory repertory = get(id);
			if(repertory==null){
				continue;
			}
			this.delete(repertory);
		}
		
		return null;
	}
}
